import LevelColler from "../../MainScene/Script/LevelColler";
import { GlobalEnum } from "../../Script/GameSpecial/GlobalEnum";
import QuadTree from "../../Script/Utils/QuadTree";

/**
 * 碰撞管理器
 */
export default class CollerManager {

    /**按碰撞体类型分类管理的八叉树 */
    protected static allTrees: { [type: number]: QuadTree };

    public static init() {
        this.allTrees = {};
        this.allTrees[GlobalEnum.CollerType.barrier] = new QuadTree(0, 100, 0, 100, 7, 5);
        this.allTrees[GlobalEnum.CollerType.role] = new QuadTree(0, 100, 0, 100, 7, 5);
        this.allTrees[GlobalEnum.CollerType.props] = new QuadTree(0, 100, 0, 100, 7, 5);
    }
    /**设置八叉树的范围 */
    public static setTreeScope(xMin, xMax,zMin, zMax) {
        for (let key in this.allTrees) {
            this.allTrees[key].init(xMin, xMax, zMin, zMax, 7, 5);
        }
    }
    public static reset() {
        for (let key in this.allTrees) {
            this.allTrees[key].reset();
        }
    }

    /**添加一组碰撞体 */
    public static addObjs(objs: LevelColler[], type: GlobalEnum.CollerType) {
        let tree = this.allTrees[type];
        for (let i = objs.length - 1; i >= 0; --i) {
            tree.insertObj(objs[i]);
        }
    }
    /**添加单个碰撞体 */
    public static addObj(obj: LevelColler, type: GlobalEnum.CollerType) {
        this.allTrees[type].insertObj(obj);
    }
    /**移除一组碰撞体 */
    public static removeObjs(objs: LevelColler[], type: GlobalEnum.CollerType) {
        let tree = this.allTrees[type];
        for (let i = objs.length - 1; i >= 0; --i) {
            tree.removeObj(objs[i]);
        }
    }
    /**移除单个碰撞体 */
    public static removeObj(obj: LevelColler, type: GlobalEnum.CollerType) {
        this.allTrees[type].removeObj(obj);
    }
    /**检测对象与指定类型的碰撞体的碰撞情况，将同步执行碰撞回调 */
    public static checkColl(obj: LevelColler, type: GlobalEnum.CollerType) {
        let a1 = obj.getAABB();
        let collers = this.allTrees[type].getObjs(obj);
        for (let i = collers.length - 1; i >= 0; --i) {
            if (LevelColler.checkAABB(a1, collers[i].getAABB())) {
                obj.onColled(collers[i]);
                collers[i].onColled(obj);
            }
        }
    }
    /**获取与对象碰撞的所有指定类型的碰撞体，不执行碰撞回调 */
    public static getCollers(obj: LevelColler, type: GlobalEnum.CollerType) {
        return this.allTrees[type].getObjs(obj);
    }
    /**获取在指定范围内的所有指定类型的碰撞体 */
    public static getScopeCollers(rect: { xMin: number, xMax: number, yMin: number, yMax: number, zMin: number, zMax: number }, type: GlobalEnum.CollerType) {
        return this.allTrees[type].getObjsByAABB(rect);
    }

}
